package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.AbnormalListAdapter;
import com.example.administrator.yanfoxconn.adapter.DNReformAdapter;
import com.example.administrator.yanfoxconn.bean.AbnormalMessage;
import com.example.administrator.yanfoxconn.bean.JIMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.SwipeListViewOne;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 安保部使用 辦事處車輛預約
 * Created by song on 2021/7/2.
 */

public class JIListActivity extends BaseActivity implements View.OnClickListener {

    private final int MESSAGE_TOAST = 2;
    private final int SUCCESS = 1;
    private final int MESSAGE_SEE_ABNORMAL = 3;

    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.lv_abnormal)
    ListView lvAbnormal;//列表
    @BindView(R.id.slv_ji_remark)
    SwipeListViewOne swipeListViewOne;
    @BindView(R.id.btn_before)
    Button btnBefore;//前一天
    @BindView(R.id.tv_date)
    TextView tvDate;//日期
    @BindView(R.id.btn_after)
    Button btnAfter;//後一天

    private List<JIMessage> jiMessageList;
    private DNReformAdapter dnReformAdapter;

    private String result;

    private String nowDateTime;//获取当前时间
    private String changeDate;//改變的時間,同時用於設置tvDate

    private Calendar noChangeTime = Calendar.getInstance();
    private Calendar changeDateTime = Calendar.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_com_see_abnormal);
        ButterKnife.bind(this);
        tvTitle.setText("車輛列表");

        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(this);
        btnBefore.setOnClickListener(this);
        btnAfter.setOnClickListener(this);
        btnAfter.setClickable(false);
        if (FoxContext.getInstance().getType().equals("JI")){

            swipeListViewOne.setVisibility(View.VISIBLE);
            lvAbnormal.setVisibility(View.GONE);
        }

        noChangeTime = Calendar.getInstance();
        SimpleDateFormat sdfAfter = new SimpleDateFormat("yyyy-MM-dd");
        nowDateTime = sdfAfter.format(noChangeTime.getTime());
        tvDate.setText(nowDateTime);
        Log.e("-----------","nowDateTime=="+nowDateTime);

        getCarList(nowDateTime);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_before:
                SimpleDateFormat sdfBefore = new SimpleDateFormat("yyyy-MM-dd");
                String dateBefore = sdfBefore.format(getBeforeDay(changeDateTime).getTime());
                getCarList(dateBefore);
                break;
            case R.id.btn_after:
                SimpleDateFormat sdfAfter = new SimpleDateFormat("yyyy-MM-dd");
                String dateAfter = sdfAfter.format(getAfterDay(changeDateTime).getTime());
                getCarList(dateAfter);
                break;
        }
    }

    private void clickSeeOrAdd() {
        dnReformAdapter.setOnClickListenerSeeOrAdd(new DNReformAdapter.OnClickListenerSeeOrAdd() {
            @Override
            public void OnClickListenerSee(int position) {
                Log.e("------", "");

                aboutAlert("確認放行！", position);
            }
        });
    }
    /**
     * 获取当前时间的前一天时间
     *
     * @param cl
     * @return
     */
    private Calendar getBeforeDay(Calendar cl) {
        //使用roll方法进行向前回滚
        //cl.roll(Calendar.DATE, -1);
        //使用set方法直接进行设置
        if (cl.equals(noChangeTime)) {

            btnAfter.setClickable(false);
        } else {
            int day = cl.get(Calendar.DATE);
            cl.set(Calendar.DATE, day - 1);

            btnAfter.setClickable(true);
        }
        return cl;
    }

    /**
     * 获取当前时间的后一天时间
     *
     * @param cl
     * @return
     */
    private Calendar getAfterDay(Calendar cl) {
        //使用roll方法进行回滚到后一天的时间
        //cl.roll(Calendar.DATE, 1);
        //使用set方法直接设置时间值
        int day = cl.get(Calendar.DATE);
        cl.set(Calendar.DATE, day + 1);
//        if (cl.compareTo(noChangeTime) > 0) {
//            ToastUtils.showShort(JIListActivity.this, "未到日期不可查詢");
//            btnAfter.setClickable(false);
//
//            day = cl.get(Calendar.DATE);
//            cl.set(Calendar.DATE, day - 1);
//        } else if (cl.compareTo(noChangeTime) < 0) {
            btnAfter.setClickable(true);
//        }
        return cl;
    }

    private void getCarList(final String textDateTime) {

        showDialog();
        final String url = Constants.HTTP_RZ_MAN_CAR_SERVLET+
                "?date=" + textDateTime;
        Log.e("-------fff--", "url==" + url);
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                Log.e("--fff---result----", result.toString());
                if (result != null) {

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray array = jsonObject.get("result").getAsJsonArray();
                        jiMessageList = new ArrayList<JIMessage>();
                        for (JsonElement type : array) {
                            JIMessage humi = gson.fromJson(type, JIMessage.class);
                            jiMessageList.add(humi);
                        }

                        changeDate = textDateTime;
                        Message message = new Message();
                        message.what = MESSAGE_SEE_ABNORMAL;
                        message.obj = jiMessageList;
                        mHandler.sendMessage(message);

                    } else if (errCode.equals("400")) {

                        changeDate = textDateTime;
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = "400";
                        mHandler.sendMessage(message);

                    }
                } else {
                    ToastUtils.showShort(JIListActivity.this, "請求不成功");
                }

            }
        }.start();
    }
    private void letGo(String applyNo,String name) {
String realName="";
        try {
            realName = URLEncoder.encode(URLEncoder.encode(FoxContext.getInstance().getName(), "UTF-8"), "UTF-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        showDialog();
        final String url = Constants.HTTP_RZ_MAN_LET_GO_SERVLET +"?apply_no="+applyNo+"&reality_end_name="+realName;
        Log.e("-------fff--", "url==" + url);
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
                Log.e("--fff---result----", result.toString());
                if (result != null) {

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {


                        Message message = new Message();
                        message.what = SUCCESS;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else if (errCode.equals("400")) {

                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = "400";
                        mHandler.sendMessage(message);

                    }
                } else {
                    ToastUtils.showShort(JIListActivity.this, "請求不成功");
                }

            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MESSAGE_TOAST://Toast彈出
                    if (msg.obj.equals("400")) {
                        jiMessageList = new ArrayList<>();
                        dnReformAdapter = new DNReformAdapter(JIListActivity.this, jiMessageList,FoxContext.getInstance().getType());
                        swipeListViewOne.setAdapter(dnReformAdapter);
                        ToastUtils.showShort(JIListActivity.this, "無車輛信息!");
                        tvDate.setText(changeDate);
                    } else {
                        ToastUtils.showShort(JIListActivity.this, msg.obj.toString());
                        tvDate.setText(nowDateTime);
                    }
                    break;
                case SUCCESS:
                    getCarList(tvDate.getText().toString());
                    break;
                case MESSAGE_SEE_ABNORMAL://列表

                    dnReformAdapter = new DNReformAdapter(JIListActivity.this, jiMessageList,FoxContext.getInstance().getType());
                    swipeListViewOne.setAdapter(dnReformAdapter);
                    clickSeeOrAdd();
                    tvDate.setText(changeDate);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void aboutAlert(String msg, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                           letGo(jiMessageList.get(position).getApply_no(),FoxContext.getInstance().getName());
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}
